package myarraylist;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 */
public class Arraylist {
    public int array[];
    public int size;
    public Arraylist(int capacity){
        this.array =new int[capacity];
    }
    public boolean isFull(){
        return size==array.length;
    }
    private  void grow(){
        this.array= Arrays.copyOf(this.array,2*array.length);
    }
    public void checkpos(int pos){
        if (pos<0||pos>size){
            throw new PostException("下标异常！！！");
        }
    }
    public void checkpos2(int pos){
        if (pos<0||pos>=size){
            throw new PostException("下标异常！！！");
        }
    }
    public void checkempty(){
        if (size==0){
            throw new EmptyException("该列表为空");
        }
    }
    public void add(int num)throws EmptyException {
        if (isFull()){
            grow();
        }
        array[size]=num;
        size++;
    }
    public void add(int num,int pos){
        try {
            checkpos(pos);
            if (isFull()){
                grow();
            }
            for (int i = size; i > pos; i--) {
                array[i]=array[i-1];
            }
            array[pos]=num;
            size++;
        }catch (PostException e){
            e.printStackTrace();
        }
    }
    public boolean contains(int num){
        for (int i = 0; i < size; i++) {
            if (array[i]==num){
                return true;
            }
        }
        return false;
    }
    public int index(int num){
     try {
         checkempty();
         for (int i = 0; i < size; i++) {
             if (array[i]==num){
                 return i;
             }
         }
         return -1;
     }catch (EmptyException e){
         e.printStackTrace();
     }
        return -1;
     }
     public int gets(int pos){
        try {
            checkempty();
            checkpos2(pos);
            return array[pos];
        }catch (EmptyException e){
            e.printStackTrace();
        }catch (PostException e){
            e.printStackTrace();
        }
        return -1;
     }
     public void set (int num, int pos){
        try {
            checkempty();
            checkpos2(pos);
            array[pos]=num;
        }catch (PostException e){
            e.printStackTrace();
        }catch (EmptyException e){
            e.printStackTrace();
        }
     }
     public void remove(int pos){
        try {
            checkempty();
            checkpos2(pos);
            for (int i = pos; i <size-1 ; i++) {
                array[i]=array[i+1];
            }
            size--;
        }catch (EmptyException e){
            e.printStackTrace();
        }catch (PostException e){
            e.printStackTrace();
        }
     }
     public void clear(){
        size =0;
     }
     public void display(){
         for (int i = 0; i < size; i++) {
             System.out.print(" "+array[i]);
         }
     }
}
